package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

//菜品模块
@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {

    //分别注入三个mapper
    //菜品mapper
    @Autowired
    private DishMapper dishMapper;

    //口味mapper
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    //分类mapper
    @Autowired
    private CategoryMapper categoryMapper;

    // 分页+条件查询
    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {
        // 1.构建菜品条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(name), Dish::getName, name);
        // 2.开启分页
        Page<Dish> page = new Page<>(pageNum, pageSize);
        // 3.分页查询
        page = dishMapper.selectPage(page, qw);

        // 4.遍历菜品列表
        List<Dish> dishList = page.getRecords();
        for (Dish dish : dishList) {
            // 根据菜品id查询口味列表
            LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
            dqw.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(dqw);
            // 封装口味列表
            dish.setFlavors(dishFlavorList);
            // 根据分类id查询分类信息
            Category category = categoryMapper.selectById(dish.getCategoryId());
            // 封装分类名称
            dish.setCategoryName(category.getName());
        }

        // 5.返回分页对象
        return page;
    }

    // 新增菜品
    @Override
    public void save(Dish dish) {
        // 1.新增菜品基本信息
        log.info("新增之前：" + dish.getId());
        dishMapper.insert(dish);
        log.info("新增之后：" + dish.getId()); // 主键返回

        // 2.遍历口味
        for (DishFlavor flavor : dish.getFlavors()) {
            // 关联菜品id
            flavor.setDishId(dish.getId());
            // 新增口味
            dishFlavorMapper.insert(flavor);
        }
        // 新增菜品时选择了分类id
        redisTemplate.delete("dish:"+dish.getCategoryId());
    }


    // 回显菜品
    @Override
    public Dish findById(Long id) {
        // 1.先查菜品
        Dish dish = dishMapper.selectById(id);
        // 2.根据菜品id查询口味
        // 2-1 构建条件
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        // 2-2  调用mapper
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(qw);
        // 3.将口味设置到菜品
        dish.setFlavors(dishFlavorList);
        //  4.返回菜品
        return dish;
    }

    // 修改菜品
    @Override
    public void updateById(Dish dish) {
        // 1.修改菜品基本信息
        dishMapper.updateById(dish);
        // 2.根据菜品id删除原来口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(qw);
        // 3.遍历新增口味
        for (DishFlavor flavor : dish.getFlavors()) {
            // 关联菜品id
            flavor.setDishId(dish.getId());
            // 口味新增
            dishFlavorMapper.insert(flavor);
        }
        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);
    }

    //删除菜品
    @Override
    public void deleteBatchIds(List<Long> ids) {
        //查询菜品是否为停售
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids); //in(1,3,5)
        qw.eq(Dish::getStatus, 1); //and status=1
        Integer count = dishMapper.selectCount(qw);
        if (count>0){
            throw new CustomException("删除的菜品状态必须为停售~~~");
        }

        // 先删菜品
        dishMapper.deleteBatchIds(ids);

        // 再删口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(wrapper);

        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);
    }


    //菜品起售、停售
    @Override
    public void updateStatus(Integer status, List<Long> ids) {
        // 构建条件对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        // 修改实体
        Dish dish = new Dish();
        dish.setStatus(status);
        // 调用mapper条件修改
        dishMapper.update(dish, wrapper);
        // 清除dish所有缓存
        // i.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        // ii.批量删除
        redisTemplate.delete(dishKeys);
    }

    // 根据分类查询菜品列表
    @Override
    public List<Dish> findListByCategoryId(Long categoryId, String name) {
        // 1.构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId != null,Dish::getCategoryId,categoryId);
        //qw.eq(Dish::getCategoryId, categoryId); // 根据分类查询
        qw.eq(Dish::getStatus, 1); // 起售状态
        qw.like(StrUtil.isNotBlank(name),Dish::getName,name);

        // 2.调用mapper查询并返回
        return dishMapper.selectList(qw);
    }


    @Autowired
    private RedisTemplate redisTemplate;
    // 菜品展示
    @Override
    public List<Dish> findList(Long categoryId, Integer status) {

        //声明返回List
        List<Dish> dishList = null;

        //定义菜品分类的key
        String dishKey = "dish:" + categoryId;

        //先查询redis是否有
        if (redisTemplate.hasKey(dishKey)){
            //如果有,直接返回
            log.info("查询redis");
            dishList = (List<Dish>) redisTemplate.opsForValue().get(dishKey);

        } else {
            log.info("查询MySQL");
            //如果没有,查询MySQL
            // 1.查询该分类下起售的菜品有哪些
            // 1-1构建条件
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(Dish::getCategoryId, categoryId);
            qw.eq(Dish::getStatus, status);
            // 1-2mapper查询
            dishList = dishMapper.selectList(qw);
            // 2.遍历菜品列表
            for (Dish dish : dishList) {
                // 根据菜品id查询口味
                List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, dish.getId()));
                // 添加到菜品中
                dish.setFlavors(dishFlavorList);
            }
            //同步到redis
            redisTemplate.opsForValue().set(dishKey,dishList);

        }

        // 3.返回结果
        return dishList;
    }
}
